package org.vectrics.common.tree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;



public class TreeHelper {
	private transient static Logger log = Logger.getLogger(TreeHelper.class);

    public TreeHelper() {
    }

    public static Node findNode(Node root, String id) {
        Node result = null;
        if (root != null) {
	        if (root.getId().equals(id)) {
	            result = root;
	        } else {
	            Iterator iter = root.getChildren().iterator();
	            while ((result == null) && (iter.hasNext())) {
	                Node node = (Node)iter.next();
	                result = findNode(node, id);
	            }
	        }
        }
        return(result);
    }
    
    
    public static int getLevel(Node node) {
        int level = 0;
        Node parent = node.getParent();
        while (parent != null) {
            level++;
            parent = parent.getParent();
        }
        return(level);
    }

    public static Collection getBranchCollection(Node node) {
        ArrayList set = new ArrayList();
        Iterator iter = node.getChildren().iterator();
        set.add(node);
        while (iter.hasNext()) {
            Node child = (Node)iter.next();
            Collection childBranchSet = getBranchCollection(child);
            set.addAll(childBranchSet);
        };
        return(set);
    }

    
	public static List getChildrenAtLevel(Node node, int relativeLevel) {
    	int actualLevel = getLevel(node) + relativeLevel + 1;
    	List levelSkillList = new ArrayList();
    	if (getLevel(node) == actualLevel) {
    		levelSkillList.add(node);
    	}
    	else {
    		Iterator iter = getBranchCollection(node).iterator(); //this.getTree().getMasterList().iterator();
    		while (iter.hasNext()) {
    			Node skill = (Node)iter.next();
    			if (getLevel(skill) == actualLevel) {
    				levelSkillList.add(skill);
    			}
    		}
    	}
    	
    	if (log.isDebugEnabled()) {
    		log.debug("getChildrenAtLevel() called - level = " + relativeLevel);
    		log.debug("getChildrenAtLevel() called - this = " + node.getId());
    		Iterator iter = levelSkillList.iterator();
    		while (iter.hasNext()) {
    			log.debug("getChildrenAtLevel() called - added child = " + ((Node)iter.next()).getId());
    			
    		}
    	}
    	return(levelSkillList);
    }
    

}